#!/bin/bash

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "========================================"
echo "           项目启动脚本"
echo "========================================"
echo

# 检查Node.js是否已安装
echo -e "${BLUE}[1/4] 检查Node.js...${NC}"
if ! command -v node &> /dev/null; then
    echo -e "${RED}❌ Node.js 未安装${NC}"
    echo
    echo "请按照以下步骤安装Node.js："
    echo "1. 访问 https://nodejs.org/"
    echo "2. 下载并安装最新的LTS版本"
    echo "3. 或者使用包管理器安装："
    echo "   Ubuntu/Debian: sudo apt install nodejs npm"
    echo "   CentOS/RHEL: sudo yum install nodejs npm"
    echo "   macOS: brew install node"
    echo "4. 安装完成后重新运行此脚本"
    echo
    read -p "按回车键退出..."
    exit 1
else
    NODE_VERSION=$(node --version)
    echo -e "${GREEN}✅ Node.js 已安装: $NODE_VERSION${NC}"
fi

# 检查pnpm是否已安装
echo
echo -e "${BLUE}[2/4] 检查pnpm...${NC}"
if ! command -v pnpm &> /dev/null; then
    echo -e "${YELLOW}❌ pnpm 未安装${NC}"
    echo
    echo "正在安装pnpm..."
    npm install -g pnpm --registry=https://registry.npmmirror.com
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ pnpm 安装失败${NC}"
        echo "请手动运行: npm install -g pnpm"
        read -p "按回车键退出..."
        exit 1
    else
        echo -e "${GREEN}✅ pnpm 安装成功${NC}"
    fi
else
    PNPM_VERSION=$(pnpm --version)
    echo -e "${GREEN}✅ pnpm 已安装: $PNPM_VERSION${NC}"
fi

# 检查package.json是否存在
echo
echo -e "${BLUE}[3/4] 检查项目文件...${NC}"
if [ ! -f "package.json" ]; then
    echo -e "${RED}❌ 未找到package.json文件${NC}"
    echo "请确保在项目根目录下运行此脚本"
    read -p "按回车键退出..."
    exit 1
else
    echo -e "${GREEN}✅ 项目文件检查通过${NC}"
fi

# 安装依赖
echo
echo -e "${BLUE}[4/4] 安装项目依赖...${NC}"
echo "正在运行: pnpm install"
pnpm install --registry=https://registry.npmmirror.com
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 依赖安装失败${NC}"
    read -p "按回车键退出..."
    exit 1
else
    echo -e "${GREEN}✅ 依赖安装成功${NC}"
fi

# 构建项目
echo
echo "========================================"
echo "           构建项目"
echo "========================================"
echo "正在运行: pnpm run build"
pnpm run build
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 项目构建失败${NC}"
    read -p "按回车键退出..."
    exit 1
else
    echo -e "${GREEN}✅ 项目构建成功${NC}"
fi

# 启动项目
echo
echo "========================================"
echo "           启动项目"
echo "========================================"
echo "正在运行: pnpm run start"
echo "项目将在 http://localhost:3000 启动"
echo "按 Ctrl+C 停止服务器"
echo
pnpm run start 